package netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;

import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;


/**
 * @Author: zhangrongqing
 * @Date: 2019/12/10 19:18
 */
public class NettyClient {
    public static void main(String[] args) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(eventLoopGroup);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true)   //设置连接数活跃
                    .handler(new ChannelInitializer<Channel>() {

                        @Override
                        protected void initChannel(Channel channel) {
                            channel.pipeline().addLast(new StringEncoder());
                            channel.pipeline().addLast(new StringDecoder());
//                            channel.pipeline().addLast(new ChannelInboundHandlerAdapter());
                            channel.pipeline().addLast(new ClientHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect("localhost", 8090).sync();
            Scanner scanner = new Scanner(System.in);
            System.out.println("输入给服务端的信息:");
            while (scanner.hasNext()) {
                String str = scanner.nextLine();
                channelFuture.channel().writeAndFlush(str);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }

    }
}
